package vn.codespot.hms;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import vn.codespot.hms.model.request.ApplyRequestModel;
import vn.codespot.hms.model.request.ApplyRequestModel.Applicant;
import vn.codespot.hms.model.request.ConfirmRequestModel;
import vn.codespot.hms.model.response.ApplyResponseModel;
import vn.codespot.hms.model.response.FeesRepsonseModel;
import vn.codespot.hms.model.response.NationalResponseModel;
import vn.codespot.hms.slidingmenu.SlidingActivityBase;
import vn.codespot.hms.slidingmenu.SlidingActivityHelper;
import vn.codespot.hms.task.ApplyTask;
import vn.codespot.hms.task.CheckingFeesTask;
import vn.codespot.hms.task.ConfirmTask;
import vn.codespot.hms.task.GetNationalTask;
import vn.codespot.hms.task.ITaskListener;
import vn.codespot.VisaVietNamAndroid.R;
import vn.codespot.hms.utils.LogUtil;
import vn.codespot.hms.utils.NumberPicker;
import vn.codespot.hms.utils.SQLiteAdapter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.zooz.android.lib.CheckoutActivity;
import com.zooz.android.lib.model.ZooZInvoice;

public class RegisterActivity extends AbstractActivity implements SlidingActivityBase {
	public static final ArrayList<String> listTransactions = new ArrayList<String>();
	
    private final int ENTRY_DATE_DIALOG = 1;

    private final int EXIT_DATE_DIALOG = 2;

    private final int PERSON_DIALOG = 3;

    private final int VISA_TYPE_DIALOG = 4;

    private final int ARRIVAL_DIALOG = 5;

    private final int PURPOSE_DIALOG = 6;

    private final int ENTRY_HOUR_DIALOG = 7;

    private final int COMPLETE_SUCCESSFUL = 11;

    private final int COMPLETE_PAY_LATER = 12;

    private final int COMPLETE_CONFIRM = 13;
    
    private final int BIRTHDAY_FIELD = 14;
    
    private final int PASSPORT_EXPIRATION_FIELD = 15;

    private final int ZOOZ_ID = 3333;

    private SlidingActivityHelper mHelper;

    private Button mRegHomeApplyNowBtn;

    private View mRegHomeLayout;

    private View mRegDetailLayout;

    private View mRegDetailPayment;

    private View mRegDetailComplete;

    private View mRegDetailInfo;

    private LinearLayout mRegDetailInfoPersons;

    private View mRegDetailContact;

    private View mRegDetailReview;

    private List<Boolean> mExpands;

    private RadioGroup mRegDetailRadios;

    private View mRegHomeItem;

    private TextView mEntryDateVal;

    private TextView mExitDateVal;

    private TextView mPersonVal;

    private TextView mVisaTypeVal;

    private String[] mVisaTypes;

    private String[] mVisaTypeVals;

    private int mVisaTypeIndex;

    private String[] mArrivals;

    private String[] mArrivalVals;

    private int mArrivalIndex;

    private String[] mPurposes;

    private String[] mEntryHours;

    private String[] mPurposeVals;

    @SuppressWarnings("unused")
    private String[] mEntryHourVals;

    private String[] mGenders;

    private String[] mGenderVals;

    private int mPurposeIndex;

    private int mHourIndex;

    private TextView mRegTitle;

    private boolean mIsInDetail;

    private boolean mIsInHome;

    private boolean mIsInDetailPayment;

    private boolean mIsInDetailComplete;

    private ImageButton mRegBtnBack;

    private ImageButton mRegBtnNext;

    private ImageButton mBtnShowMenu;

    private boolean mIsInDetailInfo;

    private boolean mIsInDetailContact;

    private boolean mIsInDetailReview;

    private Button mRegDetailInfoContBtn;

    private Button mRegDetailContactContBtn;

    private Button mRegDetailReviewProcBtn;

    private Button mRegPaymentSecureCheckoutBtn;

    private Button mRegPaymentPayLaterBtn;

    private View mRegCompleteTrackingId;

    private View mRegDetailReviewVisaTypeItem;

    private View mRegDetailReviewCouponCodeItem;

    private TextView mRegDetailReviewVisaTypeFeePerson;

    private boolean mUrgentlyVal;

    private EditText mRegDetailContactPrimaryEmail;

    private EditText mRegDetailContactRetypePrimaryEmail;

    private EditText mRegDetailContactSecondaryEmail;

    private EditText mRegDetailContactNote;

    private List<Applicant> mApplicants;

    protected boolean mApplicantsChanged;

    private Button mRegDetailReviewCouponCodeApplyBtn;

    private EditText mRegDetailReviewCouponCode;

    private TextView mRegDetailReviewVisaTypeFeeType;

    private TextView mRegDetailReviewVisaTypePerson;

    private TextView mPurposeVal;

    private TextView mEntryHourVal;

    protected TextView mArrialVal;

    private TextView mRegDetailReviewSubTotalVal;

    private TextView mRegDetailReviewSubTotalDiscountVal;

    private TextView mRegDetailReviewSubTotalMemDiscountVal;

    private TextView mRegDetailReviewSubTotalTotalVal;

    private View mRegDetailReviewSubTotalItem;

    private boolean mIsClickOnBackBtn;

    private TextView mRegCompleteTitle;

    private TextView mRegCompleteContent;

    private TextView mTrackingIdValue;

    protected List<String> mNationals;
    
    Button btnFinish;
    
    View entryhour;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mHelper = new SlidingActivityHelper(this);
        setMenu(mHelper);
        mHelper.onCreate(savedInstanceState);
        View v_behide = getLayoutInflater().inflate(R.layout.menu_layout, null);
        setBehindContentView(v_behide);
        View v = getLayoutInflater().inflate(R.layout.register_layout, null);
        setContentView(v);
        setBehindOffset(100);
        setSlidingActionBarEnabled(true);
        mBtnShowMenu = (ImageButton) v.findViewById(R.id.btnShowMenu);
        final RadioGroup radGroupMenu = (RadioGroup) v_behide.findViewById(R.id.radGroupMenu);
        final RadioButton radRegister = (RadioButton) v_behide.findViewById(R.id.radRegister);
        radRegister.setChecked(true);
        mBtnShowMenu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	hideKeyBoard(v);
                toggle();
            }
        });

        radGroupMenu.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (mHelper.isShowMenu()) {
                    Intent intent = null;
                    toggle();
                    switch (checkedId) {
                    case R.id.radRegister:
                        break;
                    case R.id.radCheckFees:
                        intent = new Intent(RegisterActivity.this, CheckFeesActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.radCheckStatus:
                        intent = new Intent(RegisterActivity.this, CheckStatusActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.radContactUs:
                        intent = new Intent(RegisterActivity.this, ContactUsActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.radHowToUse:
                        intent = new Intent(RegisterActivity.this, HowToUseActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.radSupport:
                        intent = new Intent(RegisterActivity.this, SupportActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.radDisclaimer:
                        intent = new Intent(RegisterActivity.this, DisclaimerActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.radHistory:
                        intent = new Intent(RegisterActivity.this, HistoryActivity.class);
                        startActivity(intent);
                        break;
                    }
                    radGroupMenu.check(R.id.radRegister);
                }
            }
        });

        String personValue = getIntent().getStringExtra(CheckFeesActivity.PERSON_VALUE);
        String visaTypeValue = getIntent().getStringExtra(CheckFeesActivity.VISA_TYPE_VALUE);

        mIsInDetailComplete = false;
        mIsInDetailPayment = false;
        mIsInDetail = false;
        mIsInDetailInfo = true;
        mIsInDetailContact = false;
        mIsInDetailReview = false;
        mIsInHome = true;
        mApplicantsChanged = true;
        mIsClickOnBackBtn = false;

        mExpands = new ArrayList<Boolean>();
        mApplicants = new ArrayList<ApplyRequestModel.Applicant>();
        mApplicants.add(new ApplyRequestModel.Applicant());

        mVisaTypes = this.getResources().getStringArray(R.array.visatypes);
        mVisaTypeVals = this.getResources().getStringArray(R.array.visatype_values);

        mArrivals = this.getResources().getStringArray(R.array.arrivalPorts);
        mArrivalVals = this.getResources().getStringArray(R.array.arrivalPort_values);

        mPurposes = this.getResources().getStringArray(R.array.purposes);
        mPurposeVals = this.getResources().getStringArray(R.array.purposes);

        mEntryHours = this.getResources().getStringArray(R.array.arrivalHours);
        mEntryHourVals = this.getResources().getStringArray(R.array.arrivalHoursValues);

        mGenders = this.getResources().getStringArray(R.array.genders);
        mGenderVals = this.getResources().getStringArray(R.array.gender_values);

        mRegDetailReviewSubTotalItem = findViewById(R.id.register_detail_review_subtotal_item);
        mRegDetailReviewSubTotalVal = (TextView) mRegDetailReviewSubTotalItem
                .findViewById(R.id.register_detail_review_subtotal_subtotal_value);
        mRegDetailReviewSubTotalDiscountVal = (TextView) mRegDetailReviewSubTotalItem
                .findViewById(R.id.register_detail_review_subtotal_discount_value);
        mRegDetailReviewSubTotalMemDiscountVal = (TextView) mRegDetailReviewSubTotalItem
                .findViewById(R.id.register_detail_review_subtotal_memberdiscount_value);
        mRegDetailReviewSubTotalTotalVal = (TextView) mRegDetailReviewSubTotalItem
                .findViewById(R.id.register_detail_review_subtotal_total_value);

        mRegHomeItem = findViewById(R.id.register_home_item);
        mEntryDateVal = (TextView) mRegHomeItem.findViewById(R.id.entrydate_value);
        mExitDateVal = (TextView) mRegHomeItem.findViewById(R.id.exitdate_value);
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int month = calendar.get(Calendar.MONTH);
        int year = calendar.get(Calendar.YEAR);
        mEntryDateVal.setText(createDateValue(year, month, day));
        mExitDateVal.setText(createDateValue(year, month, day+1));

        mRegTitle = (TextView) findViewById(R.id.register_title);
        mRegBtnBack = (ImageButton) findViewById(R.id.btn_back);
        mRegBtnNext = (ImageButton) findViewById(R.id.btn_next);

        mRegBtnBack.setOnClickListener(new OnClickListener() {
        	
            @Override
            public void onClick(View paramView) {
            	hideKeyBoard(paramView);
                if (isInDetail()) {
                    if (isInDetailInfo()) {
                        // Back to home when being in detail info
                        showHome();
                        togglePage(false, mRegHomeLayout, mRegDetailLayout);
                    } else if (isInDetailContact()) {
                        // Back to detail info when being in detail contact
//                        mRegDetailRadios.check(R.id.register_info_option);
                    	displayPersionalInformation(false);
                    } else if (isInDetailReview()) {
                        // Back to detail contact when being in detail review
//                        mIsClickOnBackBtn = true;
                    	displayContactInformation(false);
//                        mRegDetailRadios.check(R.id.register_contact_option);
                    } else if (isInDetailPayment()) {
                        displayDetailReview();
                        togglePage(false, mRegDetailReview, mRegDetailPayment);
                    } else if (isInDetailComplete()) {
                        displayDetailPayment();
                        togglePage(false, mRegDetailPayment, mRegDetailComplete);
                    }
                }
            }
        });

        mRegBtnNext.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
            	hideKeyBoard(arg0);
                if (isInDetail()) {
                    if (isInDetailInfo()) {
                    	displayContactInformation(true);
                    } else if (isInDetailContact()) {
//                        mRegDetailRadios.check(R.id.register_review_option);
                    	displayReviewInformation();
                    } else if (isInDetailReview()) {
                        displayDetailPayment();
                        togglePage(true, mRegDetailReview, mRegDetailPayment);
                    } else if (isInDetailPayment()) {
                        displayDetailComplete();
                        togglePage(true, mRegDetailPayment, mRegDetailComplete);
                    }
                }
            }
        });

        View entryDate = mRegHomeItem.findViewById(R.id.entrydate);
        entryDate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	hideKeyBoard(v);
                createDatePicker(mEntryDayPickerDialogUpdateListener, ENTRY_DATE_DIALOG).show();
            }
        });

        View exitDate = mRegHomeItem.findViewById(R.id.exitdate);
        exitDate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	hideKeyBoard(v);
                createDatePicker(mExitDayPickerDialogUpdateListener, EXIT_DATE_DIALOG).show();
            }
        });

        View person = mRegHomeItem.findViewById(R.id.person);
        mPersonVal = (TextView) person.findViewById(R.id.person_value);
        person.setOnClickListener(new OnClickListener() {
            @SuppressWarnings("deprecation")
			@Override
            public void onClick(View v) {
                RegisterActivity.this.showDialog(PERSON_DIALOG);
            }
        });

        mVisaTypeIndex = 0;
        View visaType = mRegHomeItem.findViewById(R.id.visatype);
        mVisaTypeVal = (TextView) visaType.findViewById(R.id.visatype_value);
        mVisaTypeVal.setText(mVisaTypes[mVisaTypeIndex]);
        visaType.setOnClickListener(new OnClickListener() {
            @SuppressWarnings("deprecation")
			@Override
            public void onClick(View v) {
                RegisterActivity.this.showDialog(VISA_TYPE_DIALOG);
            }
        });

        mArrivalIndex = 0;
        View arrival = mRegHomeItem.findViewById(R.id.arrival);
        mArrialVal = (TextView) arrival.findViewById(R.id.arrival_value);
        mArrialVal.setText(mArrivals[mArrivalIndex]);
        arrival.setOnClickListener(new OnClickListener() {
            @SuppressWarnings("deprecation")
			@Override
            public void onClick(View v) {
                RegisterActivity.this.showDialog(ARRIVAL_DIALOG);
            }
        });

        mPurposeIndex = 0;
        View purpose = mRegHomeItem.findViewById(R.id.purpose);
        mPurposeVal = (TextView) purpose.findViewById(R.id.purpose_value);
        mPurposeVal.setText(mPurposes[mPurposeIndex]);
        purpose.setOnClickListener(new OnClickListener() {
            @SuppressWarnings("deprecation")
			@Override
            public void onClick(View v) {
                RegisterActivity.this.showDialog(PURPOSE_DIALOG);
            }
        });

        mHourIndex = 0;
        entryhour = mRegHomeItem.findViewById(R.id.entryhour);
        mEntryHourVal = (TextView) entryhour.findViewById(R.id.entryhour_value);
        mEntryHourVal.setText(mEntryHours[mHourIndex]);
        entryhour.setOnClickListener(new OnClickListener() {
            @SuppressWarnings("deprecation")
			@Override
            public void onClick(View v) {
            	RegisterActivity.this.showDialog(ENTRY_HOUR_DIALOG);
            	
//            	int[] date = getDateValue(mEntryDateVal.getText().toString().trim());
//                
//                if (isEnableHourControl(date[0], date[1], date[2])) {
//                    
//                } else {
//                    Toast.makeText(RegisterActivity.this, "Date of arrival must be today or tomorrow for choosing arrival hour",
//                            Toast.LENGTH_SHORT).show();
//                }
            }
        });

        ToggleButton urgentlyBtn = (ToggleButton) mRegHomeItem.findViewById(R.id.urgently_btn);
        urgentlyBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mUrgentlyVal = isChecked;
            }
        });

        mRegDetailReviewVisaTypeItem = findViewById(R.id.register_detail_review_visatype);
        mRegDetailReviewCouponCodeItem = findViewById(R.id.register_detail_review_couponcode_item);
        mRegDetailReviewVisaTypeFeePerson = (TextView) mRegDetailReviewVisaTypeItem
                .findViewById(R.id.register_detail_review_visatype_feeperson);
        mRegDetailReviewVisaTypeFeeType = (TextView) mRegDetailReviewVisaTypeItem.findViewById(R.id.register_detail_review_visatype_type);
        mRegDetailReviewVisaTypePerson = (TextView) mRegDetailReviewVisaTypeItem.findViewById(R.id.register_detail_review_visatype_person);

        mRegDetailReviewCouponCodeApplyBtn = (Button) mRegDetailReviewCouponCodeItem
                .findViewById(R.id.register_detail_review_subtotal_subtotal_value);
        mRegDetailReviewCouponCode = (EditText) mRegDetailReviewCouponCodeItem.findViewById(R.id.register_detail_review_couponcode);

        mRegDetailInfo = findViewById(R.id.register_detail_info);
        mRegDetailInfoPersons = (LinearLayout) mRegDetailInfo.findViewById(R.id.register_detail_info_persons);
        mRegDetailContact = findViewById(R.id.register_detail_contact);
        mRegDetailReview = findViewById(R.id.register_detail_review);
        mRegDetailPayment = findViewById(R.id.register_detail_payment);
        mRegDetailComplete = findViewById(R.id.register_detail_complete);

        mRegDetailInfoContBtn = (Button) findViewById(R.id.register_detail_info_btncontinue);
        mRegDetailContactContBtn = (Button) findViewById(R.id.register_detail_contact_btncontinue);
        mRegDetailReviewProcBtn = (Button) findViewById(R.id.register_detail_review_process);
        mRegPaymentSecureCheckoutBtn = (Button) findViewById(R.id.register_payment_securecheckout);
        mRegPaymentPayLaterBtn = (Button) findViewById(R.id.register_payment_paylater);

        mRegDetailContactPrimaryEmail = (EditText) findViewById(R.id.register_detail_contact_primaryemail);
        mRegDetailContactRetypePrimaryEmail = (EditText) findViewById(R.id.register_detail_contact_retypeprimaryemail);
        mRegDetailContactSecondaryEmail = (EditText) findViewById(R.id.register_detail_contact_secondaryemail);
        mRegDetailContactNote = (EditText) findViewById(R.id.register_detail_contact_note);

        mRegCompleteTitle = (TextView) findViewById(R.id.completeTitle);
        mRegCompleteContent = (TextView) findViewById(R.id.completeContent);
        mRegCompleteTrackingId = findViewById(R.id.completeTrackingId);
        mTrackingIdValue = (TextView) mRegCompleteTrackingId.findViewById(R.id.trackingid);

        mRegDetailInfoContBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	hideKeyBoard(v);
//                boolean valid = validateInfo();
//                if (valid) {
////                    mRegDetailRadios.check(R.id.register_contact_option);
//                }
            	displayContactInformation(true);
            }
        });

        mRegDetailContactContBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	hideKeyBoard(v);
//                boolean valid = validateContact();
//                if (valid) {
////                    mRegDetailRadios.check(R.id.register_review_option);
//                }
            	displayReviewInformation();
            }
        });

        mRegDetailReviewProcBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	hideKeyBoard(v);
                displayDetailPayment();
                togglePage(true, mRegDetailReview, mRegDetailPayment);
            }
        });

        mRegPaymentSecureCheckoutBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                processPayment(true);
            }
        });

        mRegPaymentPayLaterBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	hideKeyBoard(v);
                processPayment(false);
            }
        });

        mRegDetailReviewCouponCodeApplyBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
            	hideKeyBoard(arg0);
                CheckingFeesTask task = getCheckFeesTask(true);
                task.execute();
            }
        });

//        mRegDetailRadios = (RadioGroup) findViewById(R.id.register_detail_options);
//        mRegDetailRadios.check(R.id.register_info_option);
//        mRegDetailRadios.setOnCheckedChangeListener(new OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                if (R.id.register_info_option == checkedId) {
//                    if (isInDetailContact()) {
//                        togglePage(false, mRegDetailInfo, mRegDetailContact);
//                    } else if (isInDetailReview()) {
//                        togglePage(false, mRegDetailInfo, mRegDetailReview);
//                    }
//                    displayDetailInfo();
//                } else if (R.id.register_contact_option == checkedId) {
//                    if (isInDetailInfo()) {
//                        boolean valid = validateInfo();
//                        if (valid) {
//                            displayDetailContact();
//                            togglePage(true, mRegDetailInfo, mRegDetailContact);
//                        } else {
//                            mRegDetailRadios.check(R.id.register_info_option);
//                        }
//                    } else if (isInDetailReview()) {
//                        displayDetailContact();
//                        togglePage(false, mRegDetailContact, mRegDetailReview);
//                    }
//                } else if (R.id.register_review_option == checkedId) {
//                    if (mIsClickOnBackBtn) {
//                        mIsClickOnBackBtn = false;
//                        return;
//                    }
//                    boolean valid = validateContact();
//                    if (valid) {
//                        CheckingFeesTask task = getCheckFeesTask(false);
//                        task.execute();
//                    } else {
//                        mRegDetailRadios.check(R.id.register_contact_option);
//                    }
//                }
//            }
//        });

        mRegHomeApplyNowBtn = (Button) findViewById(R.id.btn_regHome_applynow);
        mRegHomeApplyNowBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
            	hideKeyBoard(arg0);
                showDetail();
                loadApplicants(Integer.valueOf(mPersonVal.getText().toString()), mRegDetailInfoPersons);
                togglePage(true, mRegHomeLayout, mRegDetailLayout);
                mRegDetailReviewVisaTypeFeeType.setText(mVisaTypes[mVisaTypeIndex]);
                mRegDetailReviewVisaTypePerson.setText(String.valueOf(mApplicants.size()));
            }
        });

        mRegHomeLayout = findViewById(R.id.regiter_home);
        mRegDetailLayout = findViewById(R.id.register_detail);

        if (!TextUtils.isEmpty(personValue)) {
            setPersonValue(Integer.valueOf(personValue));
        } else {
            setPersonValue(1);
        }
        if (!TextUtils.isEmpty(visaTypeValue)) {
            for (int i = 0; i < mVisaTypeVals.length; i++) {
                if (mVisaTypeVals[i].equals(visaTypeValue)) {
                    mVisaTypeIndex = i;
                    mVisaTypeVal.setText(mVisaTypes[mVisaTypeIndex]);
                    break;
                }
            }
        }
        
        
        btnFinish = (Button)findViewById(R.id.btn_regHome_finish);
        btnFinish.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				hideKeyBoard(v);
				// TODO Auto-generated method stub
				Intent intent = new Intent(RegisterActivity.this, RegisterActivity.class);
				startActivity(intent);
			}
		});
        
        
        // get list from SharedData
        loadDataIntoListTransaction();
    }

    private void hideKeyBoard(View v) {
//    	this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    	if (v != null && this.getApplicationContext() != null) {
    		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        	if(imm != null){
        	        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        	}
		}
    	
    	
    }
    
    
    private void displayPersionalInformation(Boolean bNext) {
    	 showDetail();
         loadApplicants(Integer.valueOf(mPersonVal.getText().toString()), mRegDetailInfoPersons);
         togglePage(bNext, mRegDetailLayout, mRegDetailContact);
         mRegDetailReviewVisaTypeFeeType.setText(mVisaTypes[mVisaTypeIndex]);
         mRegDetailReviewVisaTypePerson.setText(String.valueOf(mApplicants.size()));
         displayDetailInfo();
    }
    
    private void displayContactInformation(Boolean bNext) {
    	boolean valid = validateInfo();
        if (valid) {
        	displayDetailContact();
        	togglePage(bNext, mRegDetailInfo, mRegDetailContact);
         }
    }
    
    private void displayReviewInformation() {
    	boolean valid = validateContact();
    	if (valid) {
          CheckingFeesTask task = getCheckFeesTask(false);
          task.execute();
    	}
    	
    }
    
    
    private boolean validateInfo() {
        for (int i = 1; i <= mApplicants.size(); i++) {
            String unknown = RegisterActivity.this.getString(R.string.unknown);
            String errMsg = "";
            boolean valid = true;
            Applicant applicant = mApplicants.get(i - 1);
            if (unknown.equals(applicant.getName())) {
                valid = false;
                errMsg = "Please, enter name for person " + i;
            } else if (unknown.equals(applicant.getNational())) {
                valid = false;
                errMsg = "Please, choose national for person " + i;
            } else if (unknown.equals(applicant.getPassport())) {
                valid = false;
                errMsg = "Please, enter passport for person " + i;
            }

            if (!valid) {
                Toast.makeText(RegisterActivity.this, errMsg, Toast.LENGTH_SHORT).show();
                return valid;
            }
        }
        return true;
    }

    private void showCompletePage(int successfulMode, String trackingIdValue) {
        displayDetailComplete();
        togglePage(true, mRegDetailPayment, mRegDetailComplete);
        String title = null;
        String content = null;
        switch (successfulMode) {
        case COMPLETE_SUCCESSFUL:
            title = getString(R.string.completeTitle_Sucsess);
            content = getString(R.string.completeContent_Success);
            break;
        case COMPLETE_PAY_LATER:
            title = getString(R.string.completeTitle_PayLater);
            content = getString(R.string.completeContent_PayLater);
            break;
        case COMPLETE_CONFIRM:
            title = getString(R.string.completeTitle_Confirm);
            content = getString(R.string.completeContent_Confirm);
            break;
        default:
            break;
        }

        mRegCompleteTitle.setText(title);
        mRegCompleteContent.setText(content);
        if (!TextUtils.isEmpty(trackingIdValue)) {
            mRegCompleteTrackingId.setVisibility(View.VISIBLE);
            mTrackingIdValue.setText(trackingIdValue);

            // Save in to history
//            SharedPreferences sharedPreferences = this.getSharedPreferences("trackingIds", MODE_PRIVATE);
//            SharedPreferences.Editor editor = sharedPreferences.edit();
//            int trackingIdLen = sharedPreferences.getInt("trackingIdCount", 0);
//            if (trackingIdLen < 10) {
//                editor.remove("trackingIdCount");
//                editor.commit();
//                editor.putInt("trackingIdCount", trackingIdLen + 1);
//                editor.putString("trackingId_" + String.valueOf(trackingIdLen), trackingIdValue);
//                editor.commit();
//            } else {
//                List<String> trkIds = new ArrayList<String>();
//                for (int i = 0; i < 10; i++) {
//                    if (i > 0) {
//                        trkIds.add(sharedPreferences.getString("trackingId_" + i, ""));
//                    }
//                    editor.remove("trackingId_" + i);
//                }
//                editor.commit();
//                trkIds.add(trackingIdValue);
//                for (int i = 0; i < 10; i++) {
//                    editor.putString("trackingId_" + i, trkIds.get(i));
//                }
//                editor.commit();
//            }
            
            SQLiteAdapter mySQLite = new SQLiteAdapter(this);
            mySQLite.openToWrite();
            mySQLite.insert(trackingIdValue);
            mySQLite.close();
            
//            listTransactions.add(0, trackingIdValue);
//            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//            SharedPreferences.Editor editor = sharedPreferences.edit();
//            
//            int size = listTransactions.size();
//            if (size > 10) {
//				size = 10;
//			}
//            
//            for (int i = 0; i < size; i++) {
//				editor.putString("HMSValue"+i, listTransactions.get(i));
//			}
//            editor.putInt("HMSSize", size);
//            editor.commit();
            
            
        } else {
            mRegCompleteTrackingId.setVisibility(View.GONE);
        }
    }

    private void loadDataIntoListTransaction() {
    	SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        //SharedPreferences.Editor editor = sharedPreferences.edit();
        
        int size = sharedPreferences.getInt("HMSSize", 0);
        for (int i = 0; i < size; i++) {
        	String value = sharedPreferences.getString("HMSValue"+i, "NULL");
			listTransactions.add(value);
			
			Log.d("HMSValue", value);
		}
        
    }
    
    public static String HMSTrackingID = "";
    private void processPayment(final boolean secureCheckOut) {
        ApplyRequestModel request = collectRegisterHomeData();
        ITaskListener listener = new ITaskListener() {
            @Override
            public void finish(Object... params) {
                try {
                    ApplyResponseModel response = (ApplyResponseModel) params[0];
                    if (response.isSuccess()) {
                        String totalValue = mRegDetailReviewSubTotalTotalVal.getText().toString().trim();
                        if (totalValue.indexOf("$") > 0) {
							totalValue = totalValue.substring(0, totalValue.length()-1);
						}
                        Double zooz_amount = Double.parseDouble(totalValue);
                        HMSTrackingID = response.getTrackingId();
                        if (secureCheckOut) {
                        	ZooZInvoice invoice = new ZooZInvoice();
                        	invoice.setInvoiceNumber(HMSTrackingID);
                            Intent intent = new Intent(RegisterActivity.this, CheckoutActivity.class);
                            intent.putExtra(CheckoutActivity.ZOOZ_APP_KEY, getString(R.string.ZOOZ_APP_KEY));
                            intent.putExtra(CheckoutActivity.ZOOZ_AMOUNT, zooz_amount);
                            intent.putExtra(CheckoutActivity.ZOOZ_CURRENCY_CODE, "USD");
                            intent.putExtra(CheckoutActivity.ZOOZ_IS_SANDBOX, true);
                            intent.putExtra(CheckoutActivity.ZOOZ_USER_EMAIL, mRegDetailContactPrimaryEmail.getText().toString().trim());
                            intent.putExtra(CheckoutActivity.ZOOZ_INVOICE, invoice);
                            startActivityForResult(intent, ZOOZ_ID);
                        } else {
                            // Pay later
                            showCompletePage(COMPLETE_PAY_LATER, response.getTrackingId());
                        }
                    } else {
                        // TODO - maybe this is confirm later
                        if ("Confirm Later!".equals(response.getErrorMessage())) {
                            Toast.makeText(RegisterActivity.this, response.getErrorMessage(), Toast.LENGTH_SHORT).show();
                            showCompletePage(COMPLETE_CONFIRM, null);
                        } else {

                            Toast.makeText(RegisterActivity.this, "Error when applying visa." + response.getErrorMessage(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (Exception e) {
                    Toast.makeText(RegisterActivity.this, "Error when applying visa.", Toast.LENGTH_SHORT).show();
                    LogUtil.e("Error when applying visa.", e);
                }
            }
        };
        ApplyTask task = new ApplyTask(RegisterActivity.this, listener, request);
        task.execute();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ZOOZ_ID) {
            switch (resultCode) {
            case Activity.RESULT_OK:
                // Transaction ID:
                // data.getStringExtra(CheckoutActivity.ZOOZ_TRANSACTION_ID)
                //showCompletePage(COMPLETE_SUCCESSFUL, data.getStringExtra(CheckoutActivity.ZOOZ_TRANSACTION_ID));
            	showCompletePage(COMPLETE_SUCCESSFUL, HMSTrackingID);
                break;
            case Activity.RESULT_CANCELED:
                if (data != null)
                    // ZOOZ error code:
                    // data.getIntExtra(CheckoutActivity.ZOOZ_ERROR_CODE, 0)
                    // ZOOZ error message:
                    // data.getStringExtra(CheckoutActivity.ZOOZ_ERROR_MSG)
                    Toast.makeText(RegisterActivity.this,
                            "Cannot complete payment with ZOOZ: " + data.getStringExtra(CheckoutActivity.ZOOZ_ERROR_MSG),
                            Toast.LENGTH_SHORT).show();
                break;

            default:
                break;
            }
        }
    }

    private boolean validateContact() {
        // Validate primary email
        boolean valid = true;
        if (TextUtils.isEmpty(mRegDetailContactPrimaryEmail.getText().toString().trim())) {
            Toast.makeText(RegisterActivity.this, "Primary email must not be empty", Toast.LENGTH_SHORT).show();
            valid = false;
        } else {
            if (!mRegDetailContactPrimaryEmail.getText().toString().trim().contains("@")) {
                mRegDetailContactPrimaryEmail.setText("");
                Toast.makeText(RegisterActivity.this, "Invalid primary email address", Toast.LENGTH_SHORT).show();
                valid = false;
            } else if (mRegDetailContactPrimaryEmail.getText().toString().trim()
                    .equals(mRegDetailContactRetypePrimaryEmail.getText().toString())) {
                valid = true;
            } else {
                mRegDetailContactRetypePrimaryEmail.setText("");
                Toast.makeText(RegisterActivity.this, "Retype primary email", Toast.LENGTH_SHORT).show();
                valid = false;
            }
        }

        // Validate secondary email
        if (valid && !TextUtils.isEmpty(mRegDetailContactSecondaryEmail.getText().toString().trim())) {
            if (!mRegDetailContactSecondaryEmail.getText().toString().trim().contains("@")) {
                mRegDetailContactSecondaryEmail.setText("");
                Toast.makeText(RegisterActivity.this, "Invalid secondary email address", Toast.LENGTH_SHORT).show();
                valid = false;
            }
        }
        return valid;
    }

    private CheckingFeesTask getCheckFeesTask(final boolean withCouponCode) {
        ITaskListener feesTaskListener = new ITaskListener() {
            @Override
            public void finish(Object... params) {
                try {
                    FeesRepsonseModel response = (FeesRepsonseModel) params[0];
                    String unitDollar = RegisterActivity.this.getString(R.string.unitDollar);
                    String unitPercent = RegisterActivity.this.getString(R.string.unitPercentage);
                    if (response.isSuccess()) {
                    	String confirm = response.getConfirm();
                    	if (Boolean.valueOf(confirm)) {
							// Show confirm check out.
                    		// Post confirm API
                    		confirmVisa();
						} else {
							mRegDetailReviewVisaTypeFeePerson.setText(response.getFeePerson() + unitDollar);
	                        mRegDetailReviewSubTotalVal.setText(response.getSubTotal() + unitDollar);
	                        mRegDetailReviewSubTotalDiscountVal.setText(response.getDiscountCoupon());
	                        mRegDetailReviewSubTotalMemDiscountVal.setText(response.getDiscountReturn());
	                        mRegDetailReviewSubTotalTotalVal.setText(response.getFeeTotal() + unitDollar);
	                        
	                        displayDetailReview();
						}
                        

//                        if (isInDetailInfo()) {
//                            togglePage(true, mRegDetailInfo, mRegDetailReview);
//                        } else if (isInDetailContact()) {
//                            togglePage(true, mRegDetailContact, mRegDetailReview);
//                        }
                        
                    } else {
                        if (!withCouponCode) {
                            mRegDetailReviewVisaTypeFeePerson.setText(RegisterActivity.this.getString(R.string.unknown));
                            mRegDetailReviewSubTotalVal.setText(RegisterActivity.this.getString(R.string.unknown));
                            mRegDetailReviewSubTotalDiscountVal.setText(RegisterActivity.this.getString(R.string.unknown));
                            mRegDetailReviewSubTotalMemDiscountVal.setText(RegisterActivity.this.getString(R.string.unknown));
                            mRegDetailReviewSubTotalTotalVal.setText(RegisterActivity.this.getString(R.string.unknown));
                        }
                        Toast.makeText(RegisterActivity.this, response.getErrorMessage(), Toast.LENGTH_SHORT).show();
//                        mRegDetailRadios.check(R.id.register_contact_option);
                    }
                } catch (Exception ignore) {
                    if (!withCouponCode) {
                        mRegDetailReviewVisaTypeFeePerson.setText(RegisterActivity.this.getString(R.string.unknown));
                        mRegDetailReviewSubTotalVal.setText(RegisterActivity.this.getString(R.string.unknown));
                        mRegDetailReviewSubTotalDiscountVal.setText(RegisterActivity.this.getString(R.string.unknown));
                        mRegDetailReviewSubTotalMemDiscountVal.setText(RegisterActivity.this.getString(R.string.unknown));
                        mRegDetailReviewSubTotalTotalVal.setText(RegisterActivity.this.getString(R.string.unknown));
                    }
                    Toast.makeText(RegisterActivity.this, "Error when checking fees.", Toast.LENGTH_SHORT).show();
//                    mRegDetailRadios.check(R.id.register_contact_option);
                }
            }
        };
        CheckingFeesTask task = new CheckingFeesTask(RegisterActivity.this, feesTaskListener, mVisaTypeVals[mVisaTypeIndex],
                mApplicants.size(), mUrgentlyVal, mEntryDateVal.getText().toString().trim(), mRegDetailReviewCouponCode.getText()
                        .toString().trim(), mRegDetailContactPrimaryEmail.getText().toString().trim(), mEntryHourVals[mHourIndex]);
        return task;
    }

    private void displayDetailInfo() {
        // Display info
        mRegDetailInfo.setVisibility(View.VISIBLE);
        mRegDetailContact.setVisibility(View.GONE);
        mRegDetailReview.setVisibility(View.GONE);
        mRegDetailPayment.setVisibility(View.GONE);
        mRegDetailComplete.setVisibility(View.GONE);
        mRegTitle.setText(RegisterActivity.this.getString(R.string.lbInfo));

        mIsInDetailInfo = true;
        mIsInDetailContact = false;
        mIsInDetailReview = false;
        mIsInDetailPayment = false;
        mIsInDetailComplete = false;

        mRegBtnBack.setVisibility(View.VISIBLE);
        mRegBtnNext.setVisibility(View.VISIBLE);
        mBtnShowMenu.setVisibility(View.GONE);
    }

    private void displayDetailContact() {
        // Display contact
        mRegDetailContact.setVisibility(View.VISIBLE);
        mRegDetailInfo.setVisibility(View.GONE);
        mRegDetailReview.setVisibility(View.GONE);
        mRegDetailPayment.setVisibility(View.GONE);
        mRegDetailComplete.setVisibility(View.GONE);
        mRegTitle.setText(RegisterActivity.this.getString(R.string.lbContactInformation));

        mIsInDetailInfo = false;
        mIsInDetailContact = true;
        mIsInDetailReview = false;
        mIsInDetailPayment = false;
        mIsInDetailComplete = false;

        mRegBtnBack.setVisibility(View.VISIBLE);
        mRegBtnNext.setVisibility(View.VISIBLE);
        mBtnShowMenu.setVisibility(View.GONE);
    }

    private void displayDetailReview() {
        // Display review
        mRegDetailReview.setVisibility(View.VISIBLE);
        mRegDetailContact.setVisibility(View.GONE);
        mRegDetailInfo.setVisibility(View.GONE);
        mRegDetailPayment.setVisibility(View.GONE);
        mRegDetailComplete.setVisibility(View.GONE);
        mRegTitle.setText(RegisterActivity.this.getString(R.string.lbReview));

        mIsInDetailInfo = false;
        mIsInDetailContact = false;
        mIsInDetailReview = true;
        mIsInDetailPayment = false;
        mIsInDetailComplete = false;

        mRegBtnBack.setVisibility(View.VISIBLE);
        mRegBtnNext.setVisibility(View.VISIBLE);
        mBtnShowMenu.setVisibility(View.GONE);
    }

    private void displayDetailPayment() {
        // Display contact
        mRegDetailContact.setVisibility(View.GONE);
        mRegDetailInfo.setVisibility(View.GONE);
        mRegDetailReview.setVisibility(View.GONE);
        mRegDetailPayment.setVisibility(View.VISIBLE);
        mRegDetailComplete.setVisibility(View.GONE);
        mRegTitle.setText(RegisterActivity.this.getString(R.string.lbSecureCheckout));

        mIsInDetailInfo = false;
        mIsInDetailContact = false;
        mIsInDetailReview = false;
        mIsInDetailPayment = true;
        mIsInDetailComplete = false;

        mRegBtnBack.setVisibility(View.VISIBLE);
        mRegBtnNext.setVisibility(View.GONE);
        mBtnShowMenu.setVisibility(View.GONE);
    }

    private void displayDetailComplete() {
        // Display contact
        mRegDetailContact.setVisibility(View.GONE);
        mRegDetailInfo.setVisibility(View.GONE);
        mRegDetailReview.setVisibility(View.GONE);
        mRegDetailPayment.setVisibility(View.GONE);
        mRegDetailComplete.setVisibility(View.VISIBLE);
        //mRegTitle.setText(RegisterActivity.this.getString(R.string.lbSecureCheckout));
        mRegTitle.setText(RegisterActivity.this.getString(R.string.lbSuccessful));

        mIsInDetailInfo = false;
        mIsInDetailContact = false;
        mIsInDetailReview = false;
        mIsInDetailPayment = false;
        mIsInDetailComplete = true;

        mRegBtnBack.setVisibility(View.GONE);
        mRegBtnNext.setVisibility(View.GONE);
        mBtnShowMenu.setVisibility(View.GONE);
    }

    private void confirmVisa() {
    	ConfirmRequestModel request = collectConfirmHomeData();
        ITaskListener listener = new ITaskListener() {
            @Override
            public void finish(Object... params) {
                try {
                	showCompletePage(COMPLETE_CONFIRM, null);
                } catch (Exception e) {
                    Toast.makeText(RegisterActivity.this, "Error when applying visa.", Toast.LENGTH_SHORT).show();
                    LogUtil.e("Error when applying visa.", e);
                }
            }
        };
        ConfirmTask task = new ConfirmTask(RegisterActivity.this, listener, request);
        task.execute();
    }
    
    private ConfirmRequestModel collectConfirmHomeData() {
    	ConfirmRequestModel confirmReqModel = new ConfirmRequestModel();
    	confirmReqModel.setVisaType(mVisaTypeVals[mVisaTypeIndex]);
    	confirmReqModel.setPurpose(mPurposeVals[mPurposeIndex]);
    	confirmReqModel.setArrivalPort(mArrivalVals[mArrivalIndex]);
    	confirmReqModel.setDateArrival(mEntryDateVal.getText().toString().trim());
    	confirmReqModel.setHourArrival(mEntryHourVals[mHourIndex]);
	    confirmReqModel.setDateExit(mExitDateVal.getText().toString().trim());
//	    confirmReqModel.setUrgently(mUrgentlyVal);
	    confirmReqModel.setPrimaryEmail(mRegDetailContactPrimaryEmail.getText().toString().trim());
	    confirmReqModel.setSecondaryEmail(mRegDetailContactSecondaryEmail.getText().toString().trim());
	    confirmReqModel.setNote(mRegDetailContactNote.getText().toString().trim());
	    confirmReqModel.setApplicants(mApplicants);
//	    String totalValue = mRegDetailReviewSubTotalTotalVal.getText().toString().trim();
//	    String value = totalValue.substring(0, totalValue.length()-1);
//	    confirmReqModel.setFees(value);
//	    confirmReqModel.setCouponCode(mRegDetailReviewCouponCode.getText().toString().trim());
	    return confirmReqModel;
    }
    

    private ApplyRequestModel collectRegisterHomeData() {
        ApplyRequestModel applyReqModel = new ApplyRequestModel();
        applyReqModel.setVisaType(mVisaTypeVals[mVisaTypeIndex]);
        applyReqModel.setPurpose(mPurposeVals[mPurposeIndex]);
        applyReqModel.setArrivalPort(mArrivalVals[mArrivalIndex]);
        applyReqModel.setDateArrival(mEntryDateVal.getText().toString().trim());
        applyReqModel.setHourArrival(mEntryHourVals[mHourIndex]);
        //applyReqModel.setHourArrival(mEntryHourVal.getText().toString().trim());
        applyReqModel.setDateExit(mExitDateVal.getText().toString().trim());
        applyReqModel.setUrgently(mUrgentlyVal);
        applyReqModel.setPrimaryEmail(mRegDetailContactPrimaryEmail.getText().toString().trim());
        applyReqModel.setSecondaryEmail(mRegDetailContactSecondaryEmail.getText().toString().trim());
        applyReqModel.setNote(mRegDetailContactNote.getText().toString().trim());
        applyReqModel.setApplicants(mApplicants);

        String totalValue = mRegDetailReviewSubTotalTotalVal.getText().toString().trim();
        applyReqModel.setFees(totalValue);

        applyReqModel.setCouponCode(mRegDetailReviewCouponCode.getText().toString().trim());
        return applyReqModel;
    }

    private void loadApplicants(int applicants, LinearLayout parentView) {
        if (!mApplicantsChanged) {
            // Do not load the applicants again with no changes made
            return;
        }

        mApplicantsChanged = false;

        parentView.removeAllViews();
        if (mNationals != null) {
            mNationals.clear();
        }
        mExpands.clear();
        // Initiate expandable flags
        for (int i = 0; i < applicants; i++) {
            mExpands.add(Boolean.FALSE);
        }

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        for (int i = 0; i < applicants; i++) {
            mExpands.set(i, Boolean.FALSE);
            final View view = inflater.inflate(R.layout.person_item, null);
            final View header = view.findViewById(R.id.header);
            TextView headerLabel = (TextView) header.findViewById(R.id.header_label);
            headerLabel.setText(headerLabel.getText().toString().trim() + " " + String.valueOf(i + 1));
            final int index = i;
            header.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean expand = !mExpands.get(index);
                    mExpands.set(index, Boolean.valueOf(expand));
                    if (expand) {
                        // Expand the group
                        // header.setBackgroundResource(R.drawable.personal_bg_header_select);
                        view.findViewById(R.id.body).setVisibility(View.VISIBLE);
                        header.findViewById(R.id.header_indicator_right).setVisibility(ImageView.GONE);
                        header.findViewById(R.id.header_indicator_down).setVisibility(ImageView.VISIBLE);
                    } else {
                        // header.setBackgroundResource(R.drawable.personal_bg_header_unselect);
                        view.findViewById(R.id.body).setVisibility(View.GONE);
                        header.findViewById(R.id.header_indicator_right).setVisibility(ImageView.VISIBLE);
                        header.findViewById(R.id.header_indicator_down).setVisibility(ImageView.GONE);
                    }
                }
            });

            final Applicant applicant = mApplicants.get(i);

            // View bodyFullname = view.findViewById(R.id.body_fullname);
            final EditText bodyFullnameVal = (EditText) view.findViewById(R.id.body_fullname_value);
            applicant.setName(RegisterActivity.this.getString(R.string.unknown));
            bodyFullnameVal.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

                }

                @Override
                public void afterTextChanged(Editable arg0) {
                    applicant.setName(bodyFullnameVal.getText().toString());

                }
            });

            final Button bodyGenderVal = (Button) view.findViewById(R.id.body_gender_value);
            bodyGenderVal.setText(mGenders[0]);
            applicant.setGender(mGenderVals[0]);
            bodyGenderVal.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                	
                    updateApplicantSingleChoiceValue(R.string.lbGender, mGenders, mGenderVals, mApplicants.get(index).getGender(), index,
                            new IApplicantUpdatingListener() {
                                @Override
                                public void update(Applicant applicant, String value) {
                                    for (int i = 0; i < mGenderVals.length; i++) {
                                        if (mGenderVals[i].equals(value)) {
                                            bodyGenderVal.setText(mGenders[i]);
                                            break;
                                        }
                                    }
                                    applicant.setGender(value);
                                }
                            });
                }
            });

            final Button dateofbirthVal = (Button) view.findViewById(R.id.body_dateofbirth_value);
            Calendar calendar = Calendar.getInstance();
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            int month = calendar.get(Calendar.MONTH);
            int year = calendar.get(Calendar.YEAR);
            String dateOfBirth = createDateValue(year, month, day);
            dateofbirthVal.setText(dateOfBirth);
            applicant.setBirthday(dateOfBirth);
            dateofbirthVal.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateApplicantDateValue(index, BIRTHDAY_FIELD, Applicant.BIRTHDAY, new IApplicantUpdatingListener() {
                        @Override
                        public void update(Applicant applicant, String value) {
                            dateofbirthVal.setText(value);
                            applicant.setBirthday(value);
                        }
                    });
                }
            });

            final Button nationalVal = (Button) view.findViewById(R.id.body_national_value);
            applicant.setNational(RegisterActivity.this.getString(R.string.unknown));
            nationalVal.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mNationals != null && !mNationals.isEmpty()) {
                        String[] nationals = mNationals.toArray(new String[mNationals.size()]);
                        updateApplicantSingleChoiceValue(R.string.lbNational, nationals, nationals, mApplicants.get(index).getNational(),
                                index, new IApplicantUpdatingListener() {
                                    @Override
                                    public void update(Applicant applicant, String value) {
                                        nationalVal.setText(value);
                                        applicant.setNational(value);
                                    }
                                });
                    } else {
                        ITaskListener listener = new ITaskListener() {
                            @Override
                            public void finish(Object... params) {
                                NationalResponseModel resp = null;
                                try {
                                    resp = (NationalResponseModel) params[0];
                                    if (resp.isSuccess()) {
                                        mNationals = resp.getNationals();
                                        String[] nationals = mNationals.toArray(new String[mNationals.size()]);
                                        updateApplicantSingleChoiceValue(R.string.lbNational, nationals, nationals, mApplicants.get(index)
                                                .getNational(), index, new IApplicantUpdatingListener() {
                                            @Override
                                            public void update(Applicant applicant, String value) {
                                                nationalVal.setText(value);
                                                applicant.setNational(value);
                                            }
                                        });
                                    } else {
                                        Toast.makeText(RegisterActivity.this, resp.getErrorMessage(), Toast.LENGTH_SHORT).show();
                                    }
                                } catch (Exception ignore) {
                                    Toast.makeText(RegisterActivity.this, "Error when getting nationals.", Toast.LENGTH_SHORT).show();
                                }
                            }
                        };
                        GetNationalTask task = new GetNationalTask(RegisterActivity.this, listener);
                        task.execute();
                    }
                }
            });

            // View bodyPnumber = view.findViewById(R.id.body_pnumber);
            final EditText bodyPnumberVal = (EditText) view.findViewById(R.id.body_pnumber_value);
            applicant.setPassport(RegisterActivity.this.getString(R.string.unknown));
            bodyPnumberVal.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

                }

                @Override
                public void afterTextChanged(Editable arg0) {
                    applicant.setPassport(bodyPnumberVal.getText().toString());
                }
            });

            // View bodyExdate = view.findViewById(R.id.body_exdate);
            final Button bodyExdateVal = (Button) view.findViewById(R.id.body_exdate_value);
            bodyExdateVal.setText(dateOfBirth);
            applicant.setPassportExp(dateOfBirth);
            bodyExdateVal.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateApplicantDateValue(index, PASSPORT_EXPIRATION_FIELD, Applicant.PASSPORT_EXP, new IApplicantUpdatingListener() {
                        @Override
                        public void update(Applicant applicant, String value) {
                            bodyExdateVal.setText(value);
                            applicant.setPassportExp(value);
                        }
                    });
                }
            });
            parentView.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
            if (i < applicants - 1) {
                View sepView = new View(RegisterActivity.this);
                sepView.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, 10));
                parentView.addView(sepView);
            }
        }
    }

    private void updateApplicantSingleChoiceValue(final int dialogTitle, String[] disValues, final String[] values, String checkedValue,
            final int index, final IApplicantUpdatingListener listener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
        builder.setTitle(dialogTitle);
        builder.setSingleChoiceItems(disValues, getCheckedValueIndex(values, checkedValue), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Applicant applicant = mApplicants.get(index);
                String value = values[which];
                listener.update(applicant, value);
                dialog.cancel();
            }
        });
        builder.create().show();
    }

    private void updateApplicantDateValue(final int index, final int type, String dateParam, final IApplicantUpdatingListener listener) {
        final Applicant applicant = mApplicants.get(index);
        int[] dateValues = getDateValue(applicant.getValue(dateParam));
        DatePickerDialog datePickerDialog = new DatePickerDialog(RegisterActivity.this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                listener.update(applicant, createDateValue(year, monthOfYear, dayOfMonth));
            }
        }, dateValues[0], dateValues[1] - 1, dateValues[2]);
        
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        	Calendar c1 = Calendar.getInstance();
            
            
            DatePicker dp = datePickerDialog.getDatePicker();
            if (type == BIRTHDAY_FIELD) {
            	c1.set(Calendar.HOUR_OF_DAY, c1.getMaximum(Calendar.HOUR_OF_DAY));
                c1.set(Calendar.MINUTE, c1.getMaximum(Calendar.MINUTE));
                c1.set(Calendar.SECOND, c1.getMaximum(Calendar.SECOND));
                c1.set(Calendar.MILLISECOND, c1.getMaximum(Calendar.MILLISECOND));
            	dp.setMaxDate(c1.getTimeInMillis());
			} else if (type == PASSPORT_EXPIRATION_FIELD){
				c1.set(Calendar.HOUR_OF_DAY, c1.getMinimum(Calendar.HOUR_OF_DAY));
	            c1.set(Calendar.MINUTE, c1.getMinimum(Calendar.MINUTE));
	            c1.set(Calendar.SECOND, c1.getMinimum(Calendar.SECOND));
	            c1.set(Calendar.MILLISECOND, c1.getMinimum(Calendar.MILLISECOND));
				dp.setMinDate(c1.getTimeInMillis());
			}
            
            dp.setCalendarViewShown(false);
            dp.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
		}
        
        
        
        datePickerDialog.show();
    }

    private int getCheckedValueIndex(String[] values, String value) {
        for (int i = 0; i < values.length; i++) {
            if (values[i].equals(value)) {
                return i;
            }
        }
        return 0;
    }

    private interface IApplicantUpdatingListener {
        void update(final Applicant applicant, final String value);
    }

    public int getDipsFromPixel(float pixels) {
        // Get the screen's density scale
        final float scale = getResources().getDisplayMetrics().density;
        // Convert the dps to pixels, based on density scale
        return (int) (pixels * scale + 0.5f);
    }

    private void togglePage(boolean next, View former, View later) {
        TranslateAnimation backward = null;
        TranslateAnimation forward = null;

        if (next) {
            backward = new TranslateAnimation(mRegHomeLayout.getWidth(), 0.0f, 0.0f, 0.0f);
            forward = new TranslateAnimation(0.0f, -mRegHomeLayout.getWidth(), 0.0f, 0.0f);
        } else {
            backward = new TranslateAnimation(0.0f, mRegHomeLayout.getWidth(), 0.0f, 0.0f);
            forward = new TranslateAnimation(-mRegHomeLayout.getWidth(), 0.0f, 0.0f, 0.0f);
        }

        backward.setDuration(300);
        backward.setInterpolator(new AccelerateInterpolator(1.0f));
        later.startAnimation(backward);

        forward.setDuration(300);
        forward.setInterpolator(new AccelerateInterpolator(1.0f));
        former.startAnimation(forward);
    }

    private void setPersonValue(int personCount) {
        mPersonVal.setText(String.valueOf(personCount));
        mApplicants.clear();
        for (int i = 0; i < personCount; i++) {
            mApplicants.add(new ApplyRequestModel.Applicant());
        }
    }

    @SuppressLint("NewApi")
    @Override
    protected Dialog onCreateDialog(int id) {
        AlertDialog.Builder builder = null;
        switch (id) {
        case PERSON_DIALOG:
            builder = new AlertDialog.Builder(RegisterActivity.this);
            builder.setTitle(R.string.lbPerson);
            final NumberPicker numberPicker = new NumberPicker(RegisterActivity.this, null,
                    Integer.valueOf(mPersonVal.getText().toString()));
            numberPicker.setGravity(Gravity.CENTER);
            builder.setView(numberPicker);
            builder.setPositiveButton(getString(R.string.titleOK), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (!mPersonVal.getText().toString().equals(String.valueOf(numberPicker.value))) {
                        // Change applicant count
                        mApplicantsChanged = true;
                        setPersonValue(numberPicker.value);
                    }
                }
            });
            
            return builder.create();
        case VISA_TYPE_DIALOG:
            builder = new AlertDialog.Builder(RegisterActivity.this);
            builder.setTitle(R.string.lbTypeOfVisa);
            builder.setSingleChoiceItems(mVisaTypes, mVisaTypeIndex, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mVisaTypeIndex = which;
                    mVisaTypeVal.setText(mVisaTypes[which]);
                    dialog.cancel();
                }
            });
            return builder.create();
        case ARRIVAL_DIALOG:
            builder = new AlertDialog.Builder(RegisterActivity.this);
            builder.setTitle(R.string.lbArrivalPort);
            builder.setSingleChoiceItems(mArrivals, mArrivalIndex, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mArrivalIndex = which;
                    mArrialVal.setText(mArrivals[mArrivalIndex]);
                    dialog.cancel();
                }
            });
            return builder.create();
        case PURPOSE_DIALOG:
            builder = new AlertDialog.Builder(RegisterActivity.this);
            builder.setTitle(R.string.lbPurpose);
            builder.setSingleChoiceItems(mPurposes, mPurposeIndex, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mPurposeIndex = which;
                    mPurposeVal.setText(mPurposes[mPurposeIndex]);
                    dialog.cancel();
                }
            });
            return builder.create();
        case ENTRY_HOUR_DIALOG:
            builder = new AlertDialog.Builder(RegisterActivity.this);
            builder.setTitle(R.string.lbArrivalHour);
            builder.setSingleChoiceItems(mEntryHours, mHourIndex, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mHourIndex = which;
                    mEntryHourVal.setText(mEntryHours[mHourIndex]);
                    dialog.cancel();
                }
            });
            return builder.create();
        default:
            return null;
        }
    }

    private DatePickerDialog createDatePicker(final IDatePickerDialogUpdatingListener listener, final int type) {
        String dateVal = "";
        String title = null;
        if (EXIT_DATE_DIALOG == type) {
            title = this.getString(R.string.lbDateOfExit);
            dateVal = mExitDateVal.getText().toString().trim();
        } else if (ENTRY_DATE_DIALOG == type) {
            title = this.getString(R.string.lbDateOfArrival);
            dateVal = mEntryDateVal.getText().toString().trim();
        }
        final int[] date = getDateValue(dateVal);
        DatePickerDialog datePickerDialog = new DatePickerDialog(RegisterActivity.this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

            	String errMsg = "Invalid date.";

                boolean valid = true;
                if (EXIT_DATE_DIALOG == type) {
                    valid = validateExitDate(year, monthOfYear, dayOfMonth);
                    errMsg += " Exit date is greater or equal than arrival date.";
                } else if (ENTRY_DATE_DIALOG == type) {
                    valid = validateEntryDate(year, monthOfYear, dayOfMonth);
                    if (!valid) {
                        errMsg += " Arrival date is greater or equal than current date.";
                    }
                }

                if (valid) {
                    listener.update(year, monthOfYear, dayOfMonth);
                    

                    // More validation for updating exit date
                    int[] exitDate = getDateValue(mExitDateVal.getText().toString().trim());
                    boolean validExitDate = validateExitDate(exitDate[0], exitDate[1] - 1, exitDate[2]);
                    if (!validExitDate) {
                        mExitDayPickerDialogUpdateListener.update(year, monthOfYear, dayOfMonth);
                    }
                    
                    if (ENTRY_DATE_DIALOG == type) {
                    	if (isEnableHourControl(year, monthOfYear, dayOfMonth)) {
    						mEntryHourVal.setVisibility(View.VISIBLE);
    						entryhour.setVisibility(View.VISIBLE);
    						mExitDayPickerDialogUpdateListener.update(year, monthOfYear, dayOfMonth+1);
    					} else {
    						mHourIndex = 0;
    						mEntryHourVal.setVisibility(View.GONE);
    						entryhour.setVisibility(View.GONE);
    						mExitDayPickerDialogUpdateListener.update(year, monthOfYear, dayOfMonth);
    					}
					}
                    
                } else {
                    Toast.makeText(RegisterActivity.this, errMsg, Toast.LENGTH_LONG).show();
                }
            }
        }, date[0], date[1] - 1, date[2]);
        if (!TextUtils.isEmpty(title)) {
            datePickerDialog.setMessage(title);
        }
        
        if (ENTRY_DATE_DIALOG == type) {
        	Calendar c1 = Calendar.getInstance();
            c1.set(Calendar.HOUR_OF_DAY, c1.getMinimum(Calendar.HOUR_OF_DAY));
            c1.set(Calendar.MINUTE, c1.getMinimum(Calendar.MINUTE));
            c1.set(Calendar.SECOND, c1.getMinimum(Calendar.SECOND));
            c1.set(Calendar.MILLISECOND, c1.getMinimum(Calendar.MILLISECOND));
            
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
            	DatePicker dp = datePickerDialog.getDatePicker();
                
                dp.setMinDate(c1.getTimeInMillis());
                dp.setCalendarViewShown(false);
                dp.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
    		}
            
		} else if (EXIT_DATE_DIALOG == type) {
			String bDateVal = mEntryDateVal.getText().toString().trim();
			final int[] bDate = getDateValue(bDateVal);
			Calendar c1 = Calendar.getInstance();
			c1.set(Calendar.YEAR, bDate[0]);
			c1.set(Calendar.MONTH, bDate[1]-1);
			c1.set(Calendar.DAY_OF_MONTH, bDate[2]);
			c1.set(Calendar.HOUR_OF_DAY, c1.getMinimum(Calendar.HOUR_OF_DAY));
            c1.set(Calendar.MINUTE, c1.getMinimum(Calendar.MINUTE));
            c1.set(Calendar.SECOND, c1.getMinimum(Calendar.SECOND));
            c1.set(Calendar.MILLISECOND, c1.getMinimum(Calendar.MILLISECOND));
            
            int maxMonth = 1;
            if (mVisaTypeIndex > 1) {
				maxMonth = 3;
			}
            
            Calendar c2 = Calendar.getInstance();
            c2.set(Calendar.YEAR, bDate[0]);
			c2.set(Calendar.MONTH, bDate[1]-1+maxMonth);
			c2.set(Calendar.DAY_OF_MONTH, bDate[2]);
			c2.set(Calendar.HOUR_OF_DAY, c2.getMaximum(Calendar.HOUR_OF_DAY));
            c2.set(Calendar.MINUTE, c2.getMaximum(Calendar.MINUTE));
            c2.set(Calendar.SECOND, c2.getMaximum(Calendar.SECOND));
            c2.set(Calendar.MILLISECOND, c2.getMaximum(Calendar.MILLISECOND));
			
			
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
            	DatePicker dp = datePickerDialog.getDatePicker();
                
                dp.setMinDate(c1.getTimeInMillis());
                dp.setMaxDate(c2.getTimeInMillis());
                dp.setCalendarViewShown(false);
                dp.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
    		}
		}
        
        
        return datePickerDialog;
    }

    private boolean isEnableHourControl(int year, int monthOfYear, int dayOfMonth) {
        Calendar now = Calendar.getInstance();
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, monthOfYear);
        cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        //cal.set(year, monthOfYear-1, dayOfMonth);

        int delta = cal.get(Calendar.DAY_OF_YEAR) - now.get(Calendar.DAY_OF_YEAR);
        return (delta == 0 || delta == 1);
    }

    private boolean validateEntryDate(int year, int monthOfYear, int dayOfMonth) {
    	return isGreaterOrEqualThanToday(year, monthOfYear, dayOfMonth);
    }

    /**
     * This checks whether the input values of date is greater or equal than today or not
     * 
     * @param year
     * @param monthOfYear
     * @param dayOfMonth
     * @return
     */
    private boolean isGreaterOrEqualThanToday(int year, int monthOfYear, int dayOfMonth) {
        Calendar now = Calendar.getInstance();
        Calendar cal = Calendar.getInstance();
        cal.set(year, monthOfYear, dayOfMonth);
        return isFirstGreaterOrEqualThanSecond(cal, now);
    }
    
    /*
     * This only validates in case exit date is less than arrival date or not
     */
    private boolean validateExitDate(int year, int monthOfYear, int dayOfMonth) {
        Calendar exit = Calendar.getInstance();
        exit.set(year, monthOfYear + 1, dayOfMonth);

        int[] arrivalDate = getDateValue(mEntryDateVal.getText().toString().trim());
        Calendar arrival = Calendar.getInstance();
        arrival.set(arrivalDate[0], arrivalDate[1], arrivalDate[2]);

        return isFirstGreaterOrEqualThanSecond(exit, arrival);
    }

    /**
     * This checks whether first date is greater or equal than second date
     * 
     * @param first
     * @param second
     * @return
     */
    private boolean isFirstGreaterOrEqualThanSecond(Calendar first, Calendar second) {
        int deltaDay = first.get(Calendar.DATE) - second.get(Calendar.DATE);
        int deltaMonth = first.get(Calendar.MONTH) - second.get(Calendar.MONTH);
        int deltaYear = first.get(Calendar.YEAR) - second.get(Calendar.YEAR);
        if (deltaYear > 0) {
            return true;
        } else if (deltaYear < 0) {
            return false;
        }

        // In case delta year is equal to 0
        if (deltaMonth > 0) {
            return true;
        } else if (deltaMonth < 0) {
            return false;
        }

        // In case delta month is equal to 0
        if (deltaDay >= 0) {
            return true;
        } else {
            return false;
        }
    }
    
    private String createDateValue(int year, int month, int day) {
        StringBuilder dateBuilder = new StringBuilder();
        if (day < 10) {
            dateBuilder.append(0);
        }
        dateBuilder.append(day);
        dateBuilder.append("-");
        if (month + 1 < 10) {
            dateBuilder.append(0);
        }
        dateBuilder.append(month + 1);
        dateBuilder.append("-");
        dateBuilder.append(year);
        return dateBuilder.toString();
    }

    private int[] getDateValue(String dateValue) {
        if (!TextUtils.isEmpty(dateValue)) {
            String[] vals = dateValue.split("-");
            if (vals != null && vals.length == 3) {
                int day = Integer.valueOf(vals[0]);
                int month = Integer.valueOf(vals[1]);
                int year = Integer.valueOf(vals[2]);
                return new int[] { year, month, day };
            }
        }
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int month = calendar.get(Calendar.MONTH);
        int year = calendar.get(Calendar.YEAR);
        return new int[] { year, month, day };
    }

    IDatePickerDialogUpdatingListener mEntryDayPickerDialogUpdateListener = new IDatePickerDialogUpdatingListener() {
        @Override
        public void update(int year, int month, int day) {
            mEntryDateVal.setText(createDateValue(year, month, day));
        }
    };

    IDatePickerDialogUpdatingListener mExitDayPickerDialogUpdateListener = new IDatePickerDialogUpdatingListener() {
        @Override
        public void update(int year, int month, int day) {
            mExitDateVal.setText(createDateValue(year, month, day));
        }
    };

    private interface IDatePickerDialogUpdatingListener {
        void update(int year, int month, int day);
    }

    /**
     * Only show register home page layout. Set gone for others
     */
    private void showHome() {
        // Set visibilities for view
        mRegHomeLayout.setVisibility(LinearLayout.VISIBLE);
        mRegDetailLayout.setVisibility(LinearLayout.GONE);

        // set flags
        mIsInDetail = false;
        mIsInHome = true;

        // Reset all the flags of detailed pages
        mIsInDetailInfo = false;
        mIsInDetailContact = false;
        mIsInDetailReview = false;
        mIsInDetailPayment = false;
        mIsInDetailComplete = false;

        // Set visibility for control buttons
        mRegBtnBack.setVisibility(View.GONE);
        mRegBtnNext.setVisibility(View.GONE);
        mBtnShowMenu.setVisibility(View.VISIBLE);

        // Change register title
        mRegTitle.setText(R.string.vnvisa);
    }

    /**
     * Only show register home page layout. Set gone for others
     */
    private void showDetail() {
        // Set visibilities for view
        mRegHomeLayout.setVisibility(LinearLayout.GONE);
        mRegDetailLayout.setVisibility(LinearLayout.VISIBLE);

        // set flags
        mIsInDetail = true;
        mIsInHome = false;

        // Reset all the flags of detailed pages
        mIsInDetailInfo = true;
        mIsInDetailContact = false;
        mIsInDetailReview = false;
        mIsInDetailPayment = false;
        mIsInDetailComplete = false;

        // Set visibility for control buttons
        mRegBtnBack.setVisibility(View.VISIBLE);
        mRegBtnNext.setVisibility(View.VISIBLE);
        mBtnShowMenu.setVisibility(View.GONE);

        // Change register title
        mRegTitle.setText(R.string.lbPassportInformation);
    }

    private boolean isInDetail() {
        return mIsInDetail;
    }

    private boolean isInDetailInfo() {
        return mIsInDetailInfo;
    }

    private boolean isInDetailContact() {
        return mIsInDetailContact;
    }

    private boolean isInDetailReview() {
        return mIsInDetailReview;
    }

    private boolean isInDetailPayment() {
        return mIsInDetailPayment;
    }

    private boolean isInDetailComplete() {
        return mIsInDetailComplete;
    }

    @SuppressWarnings("unused")
    private boolean isInHome() {
        return mIsInHome;
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
    	Intent intent = new Intent(Intent.ACTION_MAIN);
    	   intent.addCategory(Intent.CATEGORY_HOME);
    	   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	   startActivity(intent);
        return;
    };

}
